package za.org.jcicada.genss.sensor.impl;

import java.net.URISyntaxException;

import za.org.jcicada.genss.sensor.ISensorValue;
import za.org.jcicada.genss.sensor.SensorURN;

/**
 * Strategy for periodic sampling of a sensor. It will poll the current value of
 * the sensor at a specified rate.
 * 
 * @author rcrida
 */
public class StrategyPeriodic extends StrategyBase {

	private static final long serialVersionUID = 1L;
	private int period_ms;
	private long nextTime;

	public StrategyPeriodic(SensorURN sensorURN, int period_ms) {
		super(sensorURN);
		this.period_ms = period_ms;
		this.nextTime = 0L;
	}

	/**
	 * Construct strategy from string array
	 * 
	 * @param args
	 *            created by toStringArray
	 * @throws URISyntaxException
	 */
	public StrategyPeriodic(String[] args) throws URISyntaxException {
		this(new SensorURN(args[0]), Integer.parseInt(args[1]));
	}

	@Override
	public long periodic(long time) {
		if (time > nextTime) {
			ISensorValue value = getSensor().getValue();
			ISensorValue clone = new SensorValue(time, value.getValue());
			notifySample(clone);
			nextTime = nextTime + period_ms;
			if (nextTime < time) {
				nextTime = time + period_ms;
			}
		}
		return nextTime;
	}

	public String[] toStringArray() {
		return new String[] { getSensorURN().toString(), Integer.toString(period_ms) };
	}

	public int getPeriod_ms() {
		return period_ms;
	}
	
	public void setNextTime(long nextTime) {
		this.nextTime = nextTime;
	}

}
